package com.qisu.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.qisu.model.vo.PayMent;

import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;

/**
 * 结算事物 勿修改
 * 
 * @author li
 *
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class SettlementService {
	@Autowired
	private OrderService orderService;
	@Autowired
	private AccountService accountService;
	private static final Log log = LogFactory.get();

	/**
	 * 
	 * @param orderId
	 */
	public void settlement(String orderId) {
		PayMent payment = orderService.getOrderInfo(orderId);
		int chargeDiscountMoney = 0;
		int serviceDiscountMoney = 0;
		int actualPay = 0;
		Integer chargeMoney = payment.getChargeMoney();
		Integer chargeDiscount = payment.getChargeDiscount();
		Integer serviceMoney = payment.getServiceMoney();
		Integer serviceDiscount = payment.getServiceDiscount();

		if ("vip".equals(payment.getUserType())) {
			chargeDiscountMoney = (int) Math.floor(chargeMoney * (100 - chargeDiscount) / 100);
			serviceDiscountMoney = (int) Math.floor(serviceMoney * (100 - serviceDiscount) / 100);
			log.info("  chargeDiscount :{}", chargeDiscountMoney);
			log.info("  serviceDiscount :{}", serviceDiscountMoney);
		}
		actualPay = (int) Math.ceil((chargeMoney + serviceMoney - chargeDiscountMoney - serviceDiscountMoney));

		if ("5".equals(payment.getOrderType())) { // 代付
			accountService.setUserAccount(payment.getUserId());
			int refundMoney = 0;
			if (payment.getPayMoney() - actualPay > 0) {
				refundMoney = payment.getPayMoney() - actualPay;
			}
			accountService.setAgentAccount(payment.getAgentId(), refundMoney);
			accountService.insertAgentRecord(orderId, refundMoney);
			log.info(" === 代付订单:{} ===", orderId);
		} else {

			accountService.updateAccount(payment.getUserId(), actualPay);
			log.info(" === 更新钱包:{} ===", orderId);
			accountService.insertAccountRecord(payment.getUserId(), orderId, actualPay);
			log.info(" === 流水记录:{} ===", orderId);
		}
		if ("2".equals(payment.getOrderType())) {// 公众号插入退款表
			if ((payment.getPayMoney() - (chargeMoney + serviceMoney)) <= 0) {
				orderService.updateRefund(orderId, actualPay);
			} else {
				orderService.updateRefundto2(orderId, actualPay);
			}
		} else {
			orderService.updateRefund(orderId, actualPay);
		}
		orderService.updateOrder03to04(orderId, actualPay, chargeDiscountMoney, serviceDiscountMoney); // 03 -> 04
		log.info(" === 结算完成:{} ===", orderId);

	}

	public void init() {
		log.info("SETTLEMENT INITIALIZING ...");
	}
}
